package com.zgtech.kernel.configserver.configserver.repository;
import com.zgtech.kernel.configserver.configserver.model.dto.ConfigInfoDTO;
import com.zgtech.kernel.configserver.configserver.service.IConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.config.environment.Environment;
import org.springframework.cloud.config.environment.PropertySource;
import org.springframework.cloud.config.server.environment.EnvironmentRepository;
import org.springframework.cloud.config.server.environment.JdbcEnvironmentRepository;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
@Profile("myjdbc")
public class ConfigEnvironmentRepository implements EnvironmentRepository {

    @Autowired
    IConfigService configService;

    @Override
    public Environment findOne(String application, String profile, String label) {
        if (StringUtils.isEmpty(application) || StringUtils.isEmpty(profile)) return null;
        List<ConfigInfoDTO> configList = configService.getConfigList(application, profile, label);
        if(configList != null && configList.size()>0){
            Environment environment = new Environment(application,
                    StringUtils.commaDelimitedListToStringArray(profile),label,"version", "state");
            Map map = new HashMap<>();
            for(ConfigInfoDTO configInfo:configList){
                map.put(configInfo.getKey(), configInfo.getValue());
            }
            environment.add(new PropertySource(application + "_" + profile + "_" + label, map));
            return environment;
        }
        return new Environment(application,StringUtils.commaDelimitedListToStringArray(profile));
    }
}
